<template>
  <div class="bycbox">
    <div class="byccont">
      <h2 style="text-align: center">登录</h2>
      <el-form ref="loginUser" :model="user" :rules="rules">
        <el-form-item prop="username">
          <el-input
            v-model="user.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="user.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            @click="loginadd('loginUser')"
            style="width: 100%"
            :loading="loading"
            >{{ loading ? "登陆中..." : "立即登录" }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  // 组件名称
  name: "demo",
  // 组件参数 接收来自父组件的数据
  props: [],
  // 局部注册的组件
  components: {},
  // 组件状态值
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
      },
      loading: false,
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    loginadd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$axios
            .post("/api/login", this.user)
            .then((res) => {
              this.loading = false;
              this.$message.success("登录成功");
              this.$store.commit("addtoken", res.data);
              this.$router.push("/index");
            })
            .catch((error) => {
              this.$message.error(error.response.data.msg);
              this.loading = false;
              return false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  //生命周期
  created() {},
  mounted() {},
};
</script> 

<style scoped lang="scss">
.byccont {
  width: 38%;
  padding: 20px;
  box-sizing: border-box;
  border: 1px solod lightblue;
  box-shadow: lightblue 1px 1px 18px;
}
.bycbox {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
